package com.iot.utils;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.dypnsapi20170525.models.*;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.iot.enums.LanguageEnum;
import com.iot.model.SMSPhoneModel;
import com.iot.model.dto.SmsVerifyCodeDto;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class SMSUtils {
    private static final String SIGN_NAME = "VBand";

    //阿里云基础信息
    private static final String ACCESS_KEY_ID = "LTAI4FpnSCB6mc9jBB2qmNL4";

    private static final String ACCESS_KEY_SECRET = "iDPEE21PdT342n9jOWdFxRGYmLoDY0";
    //读取超时时间
    private static final int READ_TIME_OUT = 1000 * 10;
    //连接超时时间,防止系统卡死
    private static final int CONNECT_TIME_OUT = 1000 * 10;

    //成功标记
    private static final String SUCCESS = "OK";

    //只初始化一次即可
    private static com.aliyun.dypnsapi20170525.Client pnClient = null;

    private static com.aliyun.dysmsapi20170525.Client smsClient = null;


    static {
        try {
            initPnClient();
            initSmsClient();
        } catch (Exception e) {
            log.error("初始化AliPhoneUtils->client失败");
        }
    }

    //初始化客户端
    private static void initPnClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(ACCESS_KEY_ID);
        config.setAccessKeySecret(ACCESS_KEY_SECRET);
        config.setReadTimeout(READ_TIME_OUT);
        config.setConnectTimeout(CONNECT_TIME_OUT);
        pnClient = new com.aliyun.dypnsapi20170525.Client(config);
    }

    //初始化客户端
    private static void initSmsClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(ACCESS_KEY_ID);
        config.setAccessKeySecret(ACCESS_KEY_SECRET);
        config.setReadTimeout(READ_TIME_OUT);
        config.setConnectTimeout(CONNECT_TIME_OUT);
        smsClient = new com.aliyun.dysmsapi20170525.Client(config);
    }

    //构建请求对象
    private static GetMobileRequest buildMobileRequest(String token) {

        GetMobileRequest mobileRequest = new GetMobileRequest();
        mobileRequest.setAccessToken(token);
        //可要可不要，应该是随机数之类的，但是不传也没影响，可能其他接口能用上这个值吧
//        mobileRequest.setOutId("");

        return mobileRequest;
    }

    public static SMSPhoneModel getPhone(String token) {

        GetMobileRequest mobileRequest = buildMobileRequest(token);

        SMSPhoneModel aliPhoneResult = new SMSPhoneModel();
        log.info("getPhone 参数:{}", JSONObject.toJSONString(mobileRequest));

        try {

            GetMobileResponse mobileResponse = pnClient.getMobile(mobileRequest);

            GetMobileResponseBody body = mobileResponse.getBody();
            GetMobileResponseBody.GetMobileResponseBodyGetMobileResultDTO mobileResultDTO = body.getMobileResultDTO;

            if (Objects.equals(body.getCode(), SUCCESS) && mobileResultDTO != null) {
                aliPhoneResult.setIsSuccess(true);
                aliPhoneResult.setMobile(mobileResponse.getBody().getMobileResultDTO.getMobile());
            } else {
                aliPhoneResult.setErrorMsg(body.getMessage());
            }

            log.info("getPhone 返回参数:{}", JSONObject.toJSONString(mobileResponse));
            log.info("getPhone 返回body参数:{}", JSONObject.toJSONString(body));
        } catch (Exception e) {
            log.error("getPhone,异常", e);
            aliPhoneResult.setErrorMsg("请求阿里云失败");
        }

        return aliPhoneResult;
    }

    public static SMSPhoneModel sendSmsVerifyCode(SmsVerifyCodeDto dto) {
        SMSPhoneModel aliPhoneResult = new SMSPhoneModel();
        try {
            SendSmsRequest request = new SendSmsRequest();

            String phoneNumber = dto.getPhoneNumber();
            String code = dto.getCode();
            request.setTemplateCode(dto.getTemplateCode());
            request.setSignName(SIGN_NAME);
            request.setPhoneNumbers(phoneNumber);
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            log.info("getPhone 参数:{}", JSONObject.toJSONString(request));
            SendSmsResponse response = smsClient.sendSms(request);

            SendSmsResponseBody body = response.getBody();
            aliPhoneResult.setIsSuccess(Objects.equals(body.getCode(), SUCCESS));
            aliPhoneResult.setErrorMsg(body.getMessage());

            log.info("getPhone 返回参数:{}", JSONObject.toJSONString(response));
            log.info("getPhone 返回body参数:{}", JSONObject.toJSONString(body));
        } catch (Exception e) {
            log.error("getPhone,异常", e);
            aliPhoneResult.setErrorMsg("请求阿里云失败");
        }

        return aliPhoneResult;
    }


    public static void main(String[] args) {
        String token = "eyJvIjoiaU9TIiwiayI6IlRWVVIxek5OWjd2UWVZOU01VHJ3WWhVc1ZOSjZSdnMrXC9GRk15cTdRU0huOHJtTWNnZU9PRHBUUURzdjVoamFqM0JCMkdaa25zYnA1NUZJVFdSWktiOVNBTzZxbEhmT0ZqaEx2blByUHNhZnQ3bk41ZlR0ZnRrd0ZXcFA4QU9nRUVJTzg5bU1tUWNjU0ZNdEE4aTJNdElqTXloSmduWWZNM21xc3JRd0JRZ1wvbWhxOUJ6MDFQOGJvRkNRVTR0a25RRTJKa2NRUmp6RjQyZTU0Ym5uaXFYQkNkeG5cL3lBT0U5Y1F1ekdhbUZiMEN3YVU4NUxjdFpUTCtYUGUrMkNoOWMwZ0VMamEyU2MwUTBrZDc0YUpHTFdmMGdEV3N3emp1SWJleWlpZzVJM0RUUCtvTjhCMHM5ZHhpTG1yS1lLdURRd3JUSW5qN29IWXV3QnRVYWNFTG43QT09IiwiYyI6IjBFQk04ZXZVc1ZoWkxzRGpwR1lmT3hJUVN0bHIxejBtbTlQQU16RVR2SEFlREVkbWZqMTNvVEpibWdVU3FJRzk2Mlc2aXpVQjkxYUtpS3pTbHpORGpGNUR4ZUFRSWtHbmJTZHlcL3NDa0JcL3cyXC9YMEVBZkhnK0lKME1FR0JsVnpmeTd0M3RBV2hwYjh2QlFCUXJ3bXRHNEtpdFBhaGJXdE95SnpZN3U3SENXZ2x6cWJRdWhtNWVBOGFYTkxSa3FqR3AzUWxVc2M1b3ZQbk14bjdoV25FS3dhTVVWaXdRRktLeGVzcFNQcjA0cWcxdkk0Z0ZuMkJramhmTFZBejZobjNOSmFiRWNWZTNNNWVoY1ZNSGdpN2dVZlBLcndtN2E3U2p4djgrTmpKRFwvM1FKcHBRTFBkSE9vT0NoYTdMTXpWbVwvTCtjQllRcDIzaFJ4MTBYenBPMUNEZG53WURqZHFkVFhFTFh6MXNaalFXRWlBZEVsQytIb0xveFRNbnJoWlo5YUFFeWZyaFV4MUJPZkQ1ZmgrUVwvc3FYaFJETmNaMVdERXNwRFV4UHJiRGs5U2RQckc1T1pMK1krNFRlNEJxa1pvMUNsZnAxMmFUNVdJRlRBSkFqUGtVNVJFcGUyc0tENTUrSVNoZHJcLzVEeFdCejhQNUxla2w0ZnlGQit3SFhGcFhjeDc4bHVGWW96aStRUWZaZnpcL3A1OGFWc2Rha3pCdUtQTXNPWFRORE16OVozd0JWSEpEdHN3M2ZKVFhnVWM1TmxKQ2lxMXhNMTlhVHcrcHdzR01iWHZocGZsT1c5aVBsSHpVRU1tY0FXTEF1TUJCMW5FSGNUZ241OGRGdVkwdVJGSzRZdENQTkdQRDZoSkZEK3BvQVJZRFZOTmFHdEdhYktMbCs2emFjZGtyOXViSkdcLzBQZGJJZVdtTEpHV1FHcVMrd0xtXC90VHozbDNaK1lJT2s2UEF1Z2ZvejRyRGloUzhiWEZiK09Ea3Zna0NwTHRpcE9pQzlwc1RwS25GMXB2YVFGTzdROG8xdWhxMnJuUHdkVkxYTVM3RXFzeUFyY2NMait1UmUwUzFzPSJ9";

        //System.out.println(getPhone(token));
        SmsVerifyCodeDto dto = new SmsVerifyCodeDto();
        dto.setCode(String.valueOf((int)((Math.random()*9+1)*Math.pow(10,5))));
        dto.setLanguage(1);
        dto.setPhoneNumber("18229332854");
        System.out.println(sendSmsVerifyCode(dto));
    }
}
